// 天气工具类
// 提供一些常用的天气相关工具函数

// 根据温度和湿度计算露点温度
// 公式：Td = (243.04 * (ln(RH/100) + (17.625*T)/(243.04+T)))/(17.625 - ln(RH/100) - (17.625*T)/(243.04+T))
export const calculateDewPoint = (temperature, humidity) => {
  const T = parseFloat(temperature);
  const RH = parseFloat(humidity);
  
  if (isNaN(T) || isNaN(RH) || RH <= 0) {
    return '未知';
  }
  
  const term1 = Math.log(RH / 100);
  const term2 = (17.625 * T) / (243.04 + T);
  const numerator = 243.04 * (term1 + term2);
  const denominator = 17.625 - term1 - term2;
  
  const dewPoint = numerator / denominator;
  
  // 保留一位小数
  return Math.round(dewPoint * 10) / 10;
};

// 摄氏度转华氏度
export const celsiusToFahrenheit = (celsius) => {
  const C = parseFloat(celsius);
  if (isNaN(C)) {
    return '未知';
  }
  return Math.round((C * 9/5 + 32) * 10) / 10;
};

// 华氏度转摄氏度
export const fahrenheitToCelsius = (fahrenheit) => {
  const F = parseFloat(fahrenheit);
  if (isNaN(F)) {
    return '未知';
  }
  return Math.round(((F - 32) * 5/9) * 10) / 10;
};

// 根据风向角度获取风向文字
export const getWindDirection = (degree) => {
  const directions = [
    '北风', '东北风', '东风', '东南风',
    '南风', '西南风', '西风', '西北风'
  ];
  
  const deg = parseFloat(degree);
  if (isNaN(deg)) {
    return '未知';
  }
  
  // 将360度分为8个方向，每个方向45度
  const index = Math.round(deg / 45) % 8;
  return directions[index];
};

// 根据AQI值获取空气质量等级
export const getAirQualityLevel = (aqi) => {
  const aqiNum = parseInt(aqi);
  
  if (isNaN(aqiNum)) {
    return { level: '未知', color: '#999999' };
  }
  
  if (aqiNum <= 50) {
    return { level: '优', color: '#00e400' };
  } else if (aqiNum <= 100) {
    return { level: '良', color: '#ffff00' };
  } else if (aqiNum <= 150) {
    return { level: '轻度污染', color: '#ff7e00' };
  } else if (aqiNum <= 200) {
    return { level: '中度污染', color: '#ff0000' };
  } else if (aqiNum <= 300) {
    return { level: '重度污染', color: '#99004c' };
  } else {
    return { level: '严重污染', color: '#7e0023' };
  }
};

// 格式化日期时间
export const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  
  const date = new Date(dateTimeStr);
  if (isNaN(date.getTime())) return dateTimeStr;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取当前日期的星期几
export const getDayOfWeek = (dateStr) => {
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '';
  
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return weekdays[date.getDay()];
};

export default {
  calculateDewPoint,
  celsiusToFahrenheit,
  fahrenheitToCelsius,
  getWindDirection,
  getAirQualityLevel,
  formatDateTime,
  getDayOfWeek
};